package com.tnl.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biz.hunter.dao.CityDAO;
import com.biz.hunter.dao.CompanyDAO;
import com.biz.hunter.dao.JobDAO;
import com.biz.hunter.dao.JobTitleDAO;
import com.biz.hunter.db.entity.City;
import com.biz.hunter.db.entity.Company;
import com.biz.hunter.db.entity.Employer;
import com.biz.hunter.db.entity.JobDesc;
import com.biz.hunter.db.entity.JobTitle;
import com.biz.hunter.db.entity.UserInfo;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.DateUtil;
import com.tnl.web.config.controller.Authentication;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.util.qualifiers.AuditIt;

/**
 * Handles requests for the JobDesc service.
 */
@Controller
public class JobController {
	@Autowired
	private JobDAO jobDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private JobTitleDAO roleDAO;
	@Autowired
	private Authentication authentication;
	
	private static final Logger logger = LoggerFactory.getLogger(JobController.class);
	
	//职位管理首页
	@AuditIt(module = "Job", action = "job_view", description = "show the Job index page")
	@RequestMapping(value = "admin/job/manage.page", method = RequestMethod.GET)
	public String jobManagement(HttpServletRequest request, ModelMap model) {
		
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {

			logger.info("empty user id ,session is not initiallized.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}
		
		List<Company> companies = companyDAO.getALL();
		model.addAttribute("companies", companies);
		return "admin/job/joblist";
	}
//显示编辑页面
 @AuditIt(module = "Job", action = "createJob", description = "show the Job create page")
 @RequestMapping(value = "admin/job/toCreate.page", method = RequestMethod.GET)
 public String jobCreatePage(HttpServletRequest request, 
     ModelMap model) {
   
   
   JobDesc jobItem = new JobDesc();
	//   long time = jobItem.getExpiredDate();
//   jobItem.setExpiredDateStr(DateUtil.getDateStr(time));
   
   model.addAttribute("position", jobItem);
   
   
   List<Company> companies = companyDAO.getALL();
   List<City> cities = cityDAO.getALL();
   List<JobTitle> roles = roleDAO.getALL();
  
   model.addAttribute("roles", roles);
   model.addAttribute("companies", companies);
   model.addAttribute("cities", cities);
   
   return "admin/job/jobform";
 }
 
//创建职位
 @AuditIt(module = "Job", action = "createJob", description = "create Job action")
@RequestMapping(value = "admin/job/create.do", method = RequestMethod.POST)
public @ResponseBody ErrorMsg createJobDesc(HttpServletRequest request,
    ModelMap model, JobDesc job) {

  ErrorMsg msg = new ErrorMsg();


  String jobname = job.getName();
  if (StringUtils.isEmpty(jobname)) {
    logger.debug("openid is null");
    msg.setErrorcode("-1");
    msg.setMsg("职位名不能为空");
    return msg;
  }
  JobTitle jobtitle = roleDAO.getByName(jobname);
  if (jobtitle == null) {
    // 如果职位名不在数据库里，那么就把职位名设为自定义的，roleid=0
    job.setName(jobname);
    job.setRoleid(0);
  } else {
    // 如果已经是数据库里的职位名，那么就把roleid也设置为对应的
    job.setName(jobname);
    job.setRoleid(jobtitle.getId());
  }
  /*
   * if(job.getRoleid() > 0) { role = roleDAO.getById(job.getRoleid());
   * if(role != null) { job.setName(role.getName()); } }
   */

  Date now = new Date();
  job.setCreateDate(now.getTime());
  String dateStr = job.getExpiredDateStr();
  try {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdf.parse(dateStr);
    job.setExpiredDate(date.getTime());
  } catch (ParseException e) {
    msg.setErrorcode("500101");
    msg.setMsg("创建职位失败");
    return msg;
  }
  job.setCreatedby(1);

  //int companyId = employer.getCompanyId();
//  job.setCompanyId(companyId);

  // 这里要一个流水线号
  // Random rand = new Random();
  // String code = Integer.toString(rand.nextInt(99));
  String code = jobDAO.getJobCodeString();
  job.setJobCode("P-" + code);

  int id = jobDAO.save(job);
  if (id == -1) {
    msg.setErrorcode("-1");
    msg.setMsg("创建职位失败");
    return msg;
  }
  job.setId(id);
  msg.setErrorcode("0");
  msg.setMsg("成功创建职位");
  msg.setData(job);
  return msg;
}
	
	// 显示编辑页面
	@AuditIt(module = "Job", action = "editJob", description = "show the Job edit page")
	@RequestMapping(value = "admin/job/form.page", method = RequestMethod.GET)
	public String jobTitleForm(HttpServletRequest request, 
			ModelMap model, int coe) {
		
		JobDesc jobItem = null;
		
		if(coe <= 0) {
			model.addAttribute("msg", "只能编辑职位");
			return "admin/msgpage";
		} else {
			jobItem = jobDAO.getById(coe);
			if(jobItem == null) {
				model.addAttribute("msg", "没找到对应的职位");
				return "admin/msgpage";
			}
		}
		
		List<Company> companies = companyDAO.getALL();
		List<City> cities = cityDAO.getALL();
		List<JobTitle> roles = roleDAO.getALL();
		long time = jobItem.getExpiredDate();
		jobItem.setExpiredDateStr(DateUtil.getDateStr(time));
		
		model.addAttribute("position", jobItem);
		model.addAttribute("roles", roles);
		model.addAttribute("companies", companies);
		model.addAttribute("cities", cities);
		
		return "admin/job/jobform";
	}
	
	// 显示归一化职位名页面
	@AuditIt(module = "Job", action = "normaliseJob", description = "show the Job normalise page")
	@RequestMapping(value = "admin/job/normalise.page", method = RequestMethod.GET)
	public String normaliseCompany(HttpServletRequest request, Model model) {

		String jobid = request.getParameter("jobid");
		if (StringUtils.hasText(jobid)) {
			JobDesc job = jobDAO.getById(Integer.parseInt(jobid));
			model.addAttribute("job", job);
		} else {
			return "admin/errorpage";
		}

		List<JobTitle> jobtitles = roleDAO.getALL();
		model.addAttribute("jobtitles", jobtitles);

		return "admin/job/jobnormalise";
	}	

	// 搜索数据
	@RequestMapping(value = "admin/job/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<JobDesc> searchJob(jqGridRequestObject request, String sname, Integer scompanyid, Integer sstatus) {
		
		jqGridResponseObject<JobDesc> msg = new jqGridResponseObject<JobDesc>();
		
		long page = request.getPage();
		long pagesize = request.getRows();
		
		long totalrows = request.getTotalrows();
		long totalpages = 0;
		
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = jobDAO.getCountOfAll(sname,scompanyid,sstatus);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
		
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;
		
		// 获取数据
		List<Company> companies = companyDAO.getALL();
		List<JobDesc> list = jobDAO.getAllWithLimit(sname,scompanyid,sstatus,start, pagesize);
		if(list != null) {
			for (JobDesc jd : list) {
				for(Company cp : companies) {
					if(jd.getCompanyId() == cp.getId()) {
						jd.setCompanyName(cp.getName());
					}
					if(jd.getExpectcompanyid() == cp.getId()) {
						jd.setExpCompanyName(cp.getName());
					}
				}
				if(jd.getPlatformID() == 1) {
					jd.setPlatformName("推荐平台");
				} else {
					jd.setPlatformName("猎头平台");
				}
				if(jd.getStatus() ==0) {
					jd.setStatusStr("未发布");
				} else {
					jd.setStatusStr("已发布");
				}
			}
		}
		
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
		
		return msg;
	}
	
	// 删除职位
	@AuditIt(module = "Job", action = "deleteJob", description = " delete Job action")
	@RequestMapping(value = "admin/job/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteJobDesc(HttpServletRequest request, Integer jobid) {
		
		ErrorMsg msg = new ErrorMsg();

		if (jobid == null) {
			logger.debug("jobid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除的id");	
			return msg;
		}
		
		long result = jobDAO.delete(jobid);
		if(result == -1) {
			msg.setErrorcode("-2");
			msg.setMsg("删除失败");	
		} else {
			msg.setErrorcode("0");
			msg.setMsg("删除成功");
		}
		return msg;
	}
	
	// 发布职位
	@AuditIt(module = "Job", action = "createJob", description = " create Job action")
	@RequestMapping(value = "admin/job/publish.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg publishJobDesc(HttpServletRequest request, Integer jobid) {
		
		ErrorMsg msg = new ErrorMsg();

		if (jobid == null) {
			logger.debug("jobid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除的id");	
			return msg;
		}
		
		long result = jobDAO.publishJob(jobid);
		if(result == -1) {
			msg.setErrorcode("-2");
			msg.setMsg("发布失败");	
		} else {
			msg.setErrorcode("0");
			msg.setMsg("发布成功");
		}
		return msg;
	}
	
	// 更新职位
	@AuditIt(module = "Job", action = "editJob", description = "edit Job action")
	@RequestMapping(value = "admin/job/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateJobDesc(HttpServletRequest request, ModelMap model, JobDesc job) {

		ErrorMsg msg = new ErrorMsg();
		
		long jobId = job.getId();
		if(jobId <=0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定职位信息");
			return msg;
		}
		String jobName = job.getName();
		if(StringUtils.isEmpty(jobName)) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定职位名");
			return msg;
		}
		
		JobDesc jobdesc = jobDAO.getById(jobId);
		if (jobdesc == null) {
			msg.setErrorcode("500101");
			msg.setMsg("该职位不存在");
			return msg;
		}

		JobTitle role = null;
		role = roleDAO.getByName(jobName);
		if(role == null) {
			job.setRoleid(0);
		} else {
			job.setRoleid(role.getId());
		}
		
		String dateStr = job.getExpiredDateStr();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(dateStr);
			job.setExpiredDate(date.getTime());
		} catch (ParseException e) {
			msg.setErrorcode("500101");
			msg.setMsg("日期格式出问题");
			return msg;
		}
		
	    convertJobDesc(jobdesc,job);

		int row = jobDAO.update(jobdesc);
		if (row == -1) {
			msg.setErrorcode("-2");
			msg.setMsg("更新数据库出错");
			return msg;
		}
		
		msg.setErrorcode("0");
		msg.setMsg("更新数据成功");
		msg.setData(jobdesc);

		return msg;
	}

	private void convertJobDesc(JobDesc jobdesc, JobDesc job) {
		jobdesc.setName(job.getName());
		jobdesc.setRoleid(job.getRoleid());
		jobdesc.setCityId(job.getCityId());
		jobdesc.setLocation(job.getLocation());
		jobdesc.setMajorDuty(job.getMajorDuty());
		jobdesc.setEmployeeNum(job.getEmployeeNum());
		jobdesc.setReward(job.getReward());
		jobdesc.setExpectcompanyid(job.getExpectcompanyid());
		jobdesc.setExpiredDate(job.getExpiredDate());
	    jobdesc.setPlatformID(job.getPlatformID());
	    jobdesc.setCompanyId(job.getCompanyId());
	    jobdesc.setCompanyName(job.getCompanyName());
	}
	
	// 归一化职位
	@ResponseBody
	@AuditIt(module = "Job", action = "normaliseJob", description = " normalise Job action")
	@RequestMapping(value = "admin/job/normalise.do", method = RequestMethod.POST)
	public ErrorMsg normaliseJob(HttpServletRequest request, JobTitle jobtitle) {
		
		ErrorMsg msg = new ErrorMsg();
		
		JobDesc job = null;
		
		String jobid = request.getParameter("jobid");
		if (StringUtils.hasText(jobid)) {
			job = jobDAO.getById(Integer.parseInt(jobid));
		} else {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定职位信息");
			return msg;
		}
		
		if(job == null) {
			msg.setErrorcode("500101");
			msg.setMsg("职位不存在");
			return msg;
		}
		
		String op = request.getParameter("op");
		if (!StringUtils.hasText(op)) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定操作");
			return msg;
		}
		
		if(!(op.compareToIgnoreCase("create")== 0 || op.compareToIgnoreCase("subsitute")== 0)) {
			msg.setErrorcode("500101");
			msg.setMsg("指定操作不对");
			return msg;
		}
		
		if(jobtitle == null) {
			msg.setErrorcode("500101");
			msg.setMsg("提交的数据不对");
			return msg;
		}
		
		if(!StringUtils.hasText(jobtitle.getName())) {
			msg.setErrorcode("500101");
			msg.setMsg("必须职位名");
			return msg;
		}
		
		JobTitle jt = roleDAO.getByName(jobtitle.getName());
		if(op.compareToIgnoreCase("subsitute")== 0) {
			if(jt == null) {
				msg.setErrorcode("500101");
				msg.setMsg("你选择的职位名并非标准化职位名，请重新尝试");
				return msg;
			}
			// 如果已经是标准化职位名，那么进行替换
			job.setRoleid(jt.getId());
			//job.setName(jt.getName());

			int ret = jobDAO.update(job); 
			if(ret != -1) {
				msg.setErrorcode("0");
				msg.setMsg("归一化成功");
				return msg;
			}
		}
		
		if(op.compareToIgnoreCase("create")== 0) {
			if(jt != null) {
				msg.setErrorcode("500101");
				msg.setMsg("该职位名已经存在，请重新尝试");
				return msg;
			}
			
			long roleid = roleDAO.save(jobtitle);
			if(roleid <= 0) {
				msg.setErrorcode("500101");
				msg.setMsg("创建职位名数失败，请重新尝试");
				return msg;
			}
			job.setRoleid(roleid);
			job.setName(jobtitle.getName());

			int ret = jobDAO.update(job); 
			if(ret != -1) {
				msg.setErrorcode("0");
				msg.setMsg("归一化成功");
				return msg;
			}
		}
		
		msg.setErrorcode("500101");
		msg.setMsg("归一化出错，请重新尝试");
		return msg;
	}
	
	
	/*
	@RequestMapping(value = "admin/job/searchbycode.do", method = RequestMethod.GET)
	public @ResponseBody JobDesc findJobByCode(@PathVariable("code") String code) {
		logger.debug("findJobBycode");
		List<JobDesc> joblist = jobDAO.getByJobCode(code);
		if (joblist!=null && joblist.size()>0){
			return joblist.get(0);
		}
		return null;
	}
	
	@RequestMapping(value = "admin/job/toView.do", method = RequestMethod.GET)
	public @ResponseBody JobDesc getJobDesc(@PathVariable("id") long jobId) {
		logger.info("Start getjobbyid. ID="+jobId);
		
		return jobDAO.getById(jobId);
	}
	
	@RequestMapping(value = "admin/job/manage.do", method = RequestMethod.GET)
	public @ResponseBody List<JobDesc> getAllJobs() {
		logger.info("Start getAllJobDescs.");
		return jobDAO.getALL();
	}
	
	@RequestMapping(value = "admin/job/create.do", method = RequestMethod.POST)
	public @ResponseBody JobDesc createJobDesc(@RequestBody JobDesc job) {
		logger.info("Start createJobDesc.");
		Date now = new Date();
		job.setCreateDate(now.getTime());
		jobDAO.save(job);
		return job;
	}
	
	@RequestMapping(value = "admin/job/update.do", method = RequestMethod.PUT)
	public @ResponseBody JobDesc updateJobDesc(@RequestBody JobDesc job) {
		logger.info("Start createJobDesc.");
		Date now = new Date();
		job.setCreateDate(now.getTime());
		jobDAO.update(job);
		return job;
	}
	*/
	
}
